package com.zq.leave.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zq.leave.entity.User;
import com.zq.leave.entity.dto.Result;
import com.zq.leave.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baicun
 * @since 2020-06-20
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //user注册
    @PostMapping("/regist")
    public Result regist(@RequestBody User user){
        User searchUser = userService.getOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        if (searchUser != null){
            return Result.fail("用户名已存在！");
        }
        //MD5加密存进数据库
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setCreated(LocalDateTime.now());
        userService.save(user);
        return Result.success(null);
    }

    //user登录
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        //MD5加密验证
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User searchUser = userService.getOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        if (searchUser==null){
            return Result.fail("该用户不存在");
        }
        if (searchUser.getPassword().equals(user.getPassword())){
            return Result.success(searchUser);
        }else {
            return Result.fail("密码不正确！");
        }
    }

}
